$(function() {
	var role=$("input[name='loginRoleName']").val();
	$("#order-dg").datagrid({
		columns:[[
			{field:'id',hidden:true},  
	        {field:'check',checkbox:true},  
	        {field:'number',title:'订单编号',width:80},  
	        {field:'topic',title:'主题',width:100}, 
	        {field:'time',title:'时间',width:60,formatter : function(value){
                var date = new Date(value);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                var d = date.getDate();
                return y + '-' +m + '-' + d;
            }},  
	        {field:'salesOpp',title:'对应销售机会',width:100,formatter:function(value,row,index){
	        	return value ==null ? null:value.topic;
	        }},  
	        
	        {field:'orderMoney',title:'合同金额',width:60},  
	        {field:'customer',title:'对应客户',width:60,formatter:function(value,row,index){
	        	return value ==null ? null:value.name;
	        }}, 
	        {field:'state',title:'状态',width:40},  
	        {field:'delivery',title:'发货',width:40},  
	        {field:'returnGoods',title:'退货',width:40,formatter : function(value){
	        	return value?"有退货":"无退货"
            }},  
	        {field:'audit',title:'审核状态',width:40},
	        {field:'auditDate',title:'审核日期',width:60,formatter : function(value){
                var date = new Date(value);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                var d = date.getDate();
                return value==null?null:y + '-' +m + '-' + d;
            }}, 
	        {field:'auditEmployee',title:'审核人',width:60,formatter:function(value){
	        	return value ==null ? null:value.empName;
	        }},  
	        {field:'employee',title:'所有者',width:50,formatter:function(value,row,index){
	        	return value ==null ? null:value.empName+'<a title="视图" onclick="showOrder()"><i class="iconfont icon-shenhexiangmu"></i></a>';
	        }},  
	        {field:'operation',title:'操作',width:100,  
		        formatter:function(value,rec,index){ 
		        	var del='<a title="视图" onclick="showOrder()"><i class="iconfont icon-shenhexiangmu"></i></a>';
		        	if(rec.sequestration){
		        		if(role!=null&&role!="销售员"){
		        			del+='<a title="解封" onclick="setSequestration(1)"><i class="iconfont icon-jiesuo"></i></a>';
		        		}
		        	}else{
		        		if(role!=null&&role!="销售员"){
		        			del+='<a title="封存" onclick="setSequestration(0)"><i class="iconfont icon-suoding1"></i></a>';
		        		}
		        		del+='<a title="编辑" onclick="editOrder()"><i class="iconfont icon-bianji"></i></a>'+
		        		'<a title="删除" onclick="destroyOrder()"><i class="iconfont icon-msnui-trash"></i></a>';
		        	}
		        	if(rec.audit=="通过"&&rec.delivery=="未发货"){
		        		del+='<a title="发货" onclick="fahuo('+index+')"><i class="iconfont icon-huoliutongzhi"></i></a>';
		        	}
		        	// 封存
		        	if(rec.delivery=="已发货"){
		        		del+='<a title="退货" onclick="backOrder('+index+')"><i class="iconfont icon-tuihuo"></i></a>'
		        		+'<a title="结束订单" onclick="finish('+index+')"><i class="iconfont icon-biaodanwancheng2"></i></a>';
		        	}
		        	//如果我要完成订单，首先查询该订单是否有退货，没有，则需要发货单完成了才能完成订单，
		        	//有退货，则需要退货完成才能完成订单。
		            return del;    
		        }}  
	        ]] ,
	        enableFilter:[ {
	    		field : 'number',
	    		type : 'text',
	    	}, {
	    		field : 'orderMoney',
	    		type : 'numberbox',
	    		options : {
	    			precision : 1
	    		},
	    		op : [ 'equal', 'notequal', 'less', 'greater' ]
	    	} ],
	});
	$("order-adddlg").dialog({
		onClose: function(){
			// 关闭窗户后，立即销毁窗口
			$(this).dialog("destroy");
		}
	});
});
// 新增订单
function newOrder() {
	$('#order-adddlg').window('open').window('center').window('setTitle',
			'新增订单');
	$("#order-form").form('clear');
}
// 保存订单
function addOrder(){
	var form = $("#order-form");
	// 校验表单数据
	if(form.form("validate")){      
			form.ajaxSubmit({  
                 success: function(rs) { // data 保存提交后返回的数据，一般为 json 数据  
                	 if(rs.err){
         				$.messager.alert("消息",rs.err,"err");
         			}else{
         				$.messager.confirm('消息', '保存订单成功！<br><br>点击确认，新建订单明细', function(r){
         					if (r){
         						window.open("http://localhost:8080/crm/crm/order/addorderdetail/"+rs.newOrder.id);
         					}
         					// 关闭当前窗口
         					$("#order-adddlg").dialog("close");
         					$("#order-dg").datagrid("reload");
         				});
         			}
                 }  
             });    

	}
	
}
//保存编辑时订单
function saveEditOrder(){
	var form = $("#orderedit-form");
	// 校验表单数据
	if(form.form("validate")){
		$.post("crm/order/save",form.serialize(),function(rs){
			if(rs.err){
				$.messager.alert("消息",rs.err,"err");
			}else{
				$.messager.alert('消息', '保存订单成功！',"info");
				$("#order-editdlg").dialog("close");
				$("#order-dg").datagrid("reload");
			}
		});
	}
	
}
// 打开编辑订单的窗口
function editOrder() {
	var row = $('#order-dg').datagrid("getSelected");
	if(row){
		$('#order-editdlg').window('open').window('center').window('setTitle',
		'编辑订单');
		console.log(row);
		$('#orderedit-form').form('load', row);
		$('#orderedit-form').form('load',{
			//客户、员工、审批日期、审批人、创建时间、销售机会
			customerid:row.customer==null?null:row.customer.id,
			employeeid:row.employee==null?null:row.employee.id,
			auditDate1:row.auditDate==null?null:GMTToStr(row.auditDate),
			auditEmployeeid:row.auditEmployee==null?null:row.auditEmployee.id,
			time1:row.time==null?null:GMTToStr(row.time),
			salesOppid:row.salesOpp==null?null:row.salesOpp.id,
		});
		$("#confirm-order-detail").datagrid({
			toolbar: [{
				iconCls: 'icon-edit',
				handler: function(){
					window.open("http://localhost:8080/crm/crm/order/addorderdetail/"+row.id+"?type='编辑'");
				},
			},],
			url:"crm/orderDetail/getDetailByOrder/"+row.id,
			method:"GET",
		});
		$("#receivable-add-detail-dg").datagrid({
			url:"crm/receivable/getReceivableByOrder",
			queryParams: {
				orderid: row.id,
			},
			method:"GET",
		});
//		//获取订单的附件
//		var jsonStr1 = JSON.stringify(row.attachment);
//		console.log(jsonStr1);
//		console.log(row.attachment);
//		$("#order-attachment").datagrid("load",row.attachment);
	}
}
// 删除
function destroyOrder() {
	var row = $('#order-dg').datagrid('getSelected');
	if (row) {
		var rowIndex = $('#order-dg').datagrid('getRowIndex', row);
		$.messager.confirm('提示', '确定要删除该订单吗?', function(r) {
			if (r) {
				$.get("crm/order/delete/"+row.id,function(){
					$.messager.alert("提示","删除成功!");
					$('#order-dg').datagrid("reload");
                }).error(function(){
                		$.messager.alert("提示","系统错误,删除失败!",'warning');
                });
			}
		});
	}
}
//解封,封存
function setSequestration(setSequestration){
	var row = $('#order-dg').datagrid('getSelected');
	if(row){
		$.messager.confirm('提示', '确定要封存该订单吗?<br>注：封存后不可编辑和删除订单！', function(r) {
			if (r) {
				$ .ajax({
					type : "GET",
					url : "crm/order/setSequestration/"+row.id,
					data : {
						"setSequestration" : setSequestration,
					},
					success : function(rs) {
						if(rs.err){
							$.messager.alert("消息",rs.err,"err");
						}else{
							$.messager.alert('消息', '保存成功！', "info");
						}
						$("#order-dg").datagrid("reload");
					},
					error : function() {
						$.messager.alert("保存失败");
					}		
				});
			}
		});
	}
}
// 视图
function showOrder() {

}
//发货
function fahuo(index){
	$('#order-dg').datagrid('selectRow',index);
	var row = $('#order-dg').datagrid('getSelected');
	if (row) {
		$('#order-fahuodlg').window('open').window('center');
		$('#confirm-order-detail').datagrid({
			url:"crm/orderDetail/getDetailByOrder/"+row.id,
			method:"GET",
			queryParams: {
				state: '未发货',
			},
			onLoadSuccess:function(){
				$('#confirm-order-detail').datagrid("selectAll");
			}
		});
		$("#confirm-information").form('load', row);
	}
}
//保存发货
function savefahuo() {
	var orderid = $("#confirm-information input[name='id']").val();
	var delivery=$("#confirm-information input[name='delivery']").val();
	var getRows = $('#confirm-order-detail').datagrid('getRows')// 获取当前的数据行
	var getChecked= $('#confirm-order-detail').datagrid("getSelections");
	var rows;
	var delivery_value;
	if(delivery=1){//部分发货
		// 返回复选框选中的所有行.
		rows=getChecked;
		if(getChecked.length=getRows.length){
			delivery_value="已发货";
		}else{
			delivery_value="部分发货";
		}
	}else{//全部发货
		rows=getRows;
		delivery_value="已发货";
	}
	if (getChecked.length<1) {
		$.messager.alert("提示", "您还没有选中产品呐！", "warning");
	} else {
		$.ajax({
			url : 'crm/deliveryDetail/saveDeliveryDetail/' + orderid,
			type : 'post',
			dataType : 'json',
			data : {
				delivery:delivery_value,
				"orderDetails" : JSON.stringify(rows),
			// JSON.stringify() 方法用于将JavaScript值转换为 JSON
			// 字符串，缺少此句传到后台的则为空值
			},
			success : function(response) { // 后台返回的要显示的消息
				if(response.err){
					$.messager.alert("消息","错误了！","error");
				}else{
					$.messager.alert("消息","发货成功！","info");
					$('#order-fahuodlg').window('close');
					$("#order-dg").datagrid("reload");
				}
			}
		});
	}
}
// 退货
function backOrder(index){
	$('#order-dg').datagrid('selectRow',index);
	var row = $('#order-dg').datagrid('getSelected');
	if (row) {
		$('#order-backdlg').window('open').window('center');
		$('#confirm-fahuo-detail').datagrid({
			url : "crm/orderDetail/getDetailByOrder/" + row.id,
			method : "GET",
			queryParams : {
				state: '已发货',
			},
			onLoadSuccess : function() {
				$('#confirm-order-detail').datagrid("selectAll");
			}
		});
		$("#confirm-fahuo-detail").form('load', row);
		$("input[name='order-back-orderid']").val(row.id);
	}
}
// 保存退货
function savetuihuo(){
	var form = $("#order-back-form");
	var rows;
	// 校验表单数据
	if(form.form("validate")){
		var orderid = $("#order-back-form input[name='order-back-orderid']").val();
		var tp = $("#order-back-form input[name='tp']:checked").val();
		var note = $("#order-back-form input[name='note']").val();
		if(tp==0){//整单退
			rows = $('#confirm-fahuo-detail').datagrid('getRows')// 获取当前的数据行
		}else{
			// 返回复选框选中的所有行.
			rows = $('#confirm-fahuo-detail').datagrid("getSelections");
		}
		var a=$('#confirm-fahuo-detail').datagrid("getSelections");
		var getChecked=$('#confirm-fahuo-detail').datagrid("getChecked");
		console.log(rows);
		console.log(a);
		console.log(getChecked);
		if (rows.length == 0) {
			$.messager.alert("提示", "您还没有选中产品呐！", "warning");
		} else {
			$.ajax({
				url : 'crm/backDetail/saveBackDetail/' + orderid,
				type : 'post',
				dataType : 'json',
				data : {
					"orderDetails" : JSON.stringify(rows),
					"note":note,
				// JSON.stringify() 方法用于将JavaScript值转换为 JSON
				// 字符串，缺少此句传到后台的则为空值
				},
				success : function(response) { // 后台返回的要显示的消息
					if(response.err){
						$.messager.alert("消息","错误了！","error");
					}else{
						$.messager.alert("消息","退货成功！","info");
						$('#order-backdlg').window('close');
						$("#order-dg").datagrid("reload");
					}
				}
			});
		}
	}
}
//结束订单
function finish(index){
	$('#order-dg').datagrid('selectRow',index);
	var row = $('#order-dg').datagrid('getSelected');
	if (row) {
		$.messager.confirm("提示","要结束订单吗？",function(r){
			if(r){
				$.get("crm/order/finishOrder/"+row.id,function(rs){
					if(rs.success){
						$.messager.alert("提示","成功!","info");
					}else{
						$.messager.alert("提示",rs.err,"info");
					}
					$('#order-dg').datagrid("reload");
                }).error(function(){
                		$.messager.alert("提示","请求失败 !",'warning');
                });
			}
		});
	}
}
// 统计
function compute() {// 计算函数
	var rows = $('#order-dg').datagrid('getRows')// 获取当前的数据行
	var ptotal = 0// 计算listprice的总和
	, utotal = 0;// 统计unitcost的总和
	for (var i = 0; i < rows.length; i++) {
		ptotal += parseFloat(rows[i]['orderMoney']);
		utotal += parseFloat(rows[i]['receivableMoney']);
	}
	// 新增一行显示统计信息
	$('#order-dg').datagrid('appendRow', {
		number : '<b>总计：</b>',
		orderMoney : ptotal,
		receivableMoney : utotal
	});
}
function GMTToStr(time){
    let date = new Date(time)
    let Str=date.getFullYear() + '-' +
    (date.getMonth() + 1) + '-' + 
    date.getDate() + ' ' + 
    date.getHours() + ':' + 
    date.getMinutes() + ':' + 
    date.getSeconds()
    return Str;
}